<?php
/**
 * 
 */

/**
* 
*/
class wx_bonus_account_biz
{

	
	function __construct()
	{
		$this->bonus_account = load('m/wx_bonus_account_m');
		$this->user          = load('m/users_m');
	}
	//这里有一个问题 需要解决未关注且未注册用户,这部分不要变
	public function toAccount($openid,$amount,$bonus_id,$expire_time,$bonus_user_id = 0){
		 $uinfo = $this->user->wxuser($openid);
		// if (empty($uinfo) || empty($amount)) {
		// 	return false;//暂时放弃控制用户账户
		// }

		if (empty($amount)) {
			return false;
		}
		//防止发放同一个红包
		$ret = $this->bonus_account->get("and openid = '$openid' and bonus_id =$bonus_id and bonus_user_id =$bonus_user_id");
		if (!empty($ret)) {
			return true;
		}

		//$le_coin1 = $uinfo['le_coin'];
		$elem = array();
		$elem['openid'] = $openid;
		$elem['user_id'] = isset($uinfo['user_id']) ? $uinfo['user_id'] : 0;
		$elem['amount'] = $amount;
		$elem['bonus_id'] = $bonus_id;
		$elem['bonus_user_id'] = $bonus_user_id;
		$elem['expire_time'] = $expire_time;
		$elem['le_coin1'] = 0;
		$elem['le_coin2'] = 0;
		$elem['add_time'] = time();
		$elem['status'] = 0;
		$elem['bonus_sn'] = $this->bonus_sn();
		$ret1 = $this->bonus_account->add($elem);
		return $ret1;
		//放弃控制用户账户
		// $new_uinfo = array();
		// $new_uinfo['le_coin'] = $le_coin1 + $amount;
		// $ret2 = $this->user->update($uinfo['user_id'],$new_uinfo);
	}

	public function useBonus($id,$orderid,$orderamount,$storeid){
		
		$baccount = $this->bonus_account->get($id);
		if (empty($baccount) || !empty($baccount['used_time'])) {
			return false;
		}

		$openid = $baccount['openid'];
		
		$elem = array();
		$elem['order_id'] = $orderid;
		$elem['order_amount'] = $orderamount;
		$elem['storeid'] = $storeid;
		$elem['le_coin3'] = 0;
		$elem['le_coin4'] = 0;
		$elem['used_time'] = time();

		$ret =  $this->bonus_account->update($id,$elem);
		return $ret;
	}

	
	//
	public function bonus_sn()
	{
		$bonus_sn ='';
		$day = date('d');
		do {
			$rand.=sprintf('%06d',rand(1,100000));
			$bonus_sn = $day.$rand;
			$count = $this->bonus_account->count("AND bonus_sn = '$bonus_sn' ");
		} while ($count||strlen($bonus_sn) < 8);
		return $bonus_sn;
	}





}